import { useCallback, useEffect, useState } from 'preact/hooks';
import { downloadFile, getFiles, getIps } from '../api/api.ts';
import './Home.css'
import { useFileUpload } from "../hooks/useFileUpload.ts";
import { fi } from "zod/v4/locales";

interface FileData {
    type: 'file' | 'text';
    content: string;
    source: string;
}

// 简易 Toast 组件（可替换为成熟 UI 库）
const Toast = ({ message, show, onClose }: { message: string; show: boolean; onClose: () => void }) => {
    useEffect(() => {
        if (show) {
            const timer = setTimeout(onClose, 2000);
            return () => clearTimeout(timer);
        }
    }, [show, onClose]);

    if (!show) return null;
    return (
        <div style={{
            position: 'fixed',
            top: '50px',
            left: '50%',
            transform: 'translateX(-50%)',
            backgroundColor: '#333',
            color: '#fff',
            padding: '10px 20px',
            borderRadius: '6px',
            zIndex: 1000,
            fontSize: '14px'
        }}>
            {message}
        </div>
    );
};

const Home = () => {
    const [select, setSelect] = useState<string | undefined>();
    const [ips, setIps] = useState<string[]>([]);
    const [files, setFiles] = useState<FileData[]>([]);
    const [loading, setLoading] = useState(false);
    const [toast, setToast] = useState({ show: false, message: '' });
    const { upload, progress, loading: uploadLoading } = useFileUpload();

    const showToast = (msg: string) => {
        setToast({ show: true, message: msg });
    };

    const handleSubmit = async (formData: FormData) => {
        setLoading(true);
        try {
            const res = await upload(formData);
            showToast(res.message || '发送成功');
        } catch (error: any) {
            showToast(error.message || '发送失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    const onCloseToast = useCallback(() => {
        setToast({ show: false, message: '' });
    }, [])

    // 轮询文件列表
    useEffect(() => {
        const fetchFiles = async () => {
            await Promise.all([
                getFiles()
                    .then((res) => {
                        setFiles((oldFiles) => {
                            if (res.files.length !== oldFiles.length) {
                                return res.files || [];
                            }
                            return oldFiles;
                        });
                    })
                    .catch(() => {
                        if (files.length) {
                            setFiles([]);
                            showToast('获取文件失败');
                        }
                    }), getIps()
                        .then((res) => {
                            const ipList = res.ips || [];
                            setIps((oldIps) => {
                                if (ipList.length !== oldIps.length) {
                                    setSelect(ipList[0]);
                                    return ipList;
                                }
                                return oldIps;
                            });
                        })
                        .catch(() => {
                            if (ips.length) {
                                setIps([]);
                                setSelect(undefined);
                                showToast('无法获取设备列表');
                            }
                        })
            ])
        };

        fetchFiles();
        const timer = setInterval(fetchFiles, 2000);
        return () => clearInterval(timer);
    }, []);

    return (
        <div>

            <div className="home-container">
                <header className="header">
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                        <h2>文件传输助手</h2>
                        <div style={{ fontSize: '14px', fontWeight: 'bold', color: 'green' }}>{progress !== null ? `进度: ${progress}%` : ''}</div>
                    </div>
                    <select
                        value={select || ''}
                        onChange={(e) => setSelect(e.currentTarget.value)}
                        disabled={ips.length === 0}
                        aria-label="选择目标设备"
                    >
                        {ips.length === 0 ? (
                            <option value="">无可用设备</option>
                        ) : (
                            ips.map((ip) => (
                                <option key={ip} value={ip}>
                                    {ip}
                                </option>
                            ))
                        )}
                    </select>
                </header>

                <main className="content">
                    {files.length === 0 ? (
                        <div className="empty-state">暂无文件或文本</div>
                    ) : (
                        <div className="file-list">
                            {files.map((item, index) => (
                                <div key={index} className="file-item">
                                    <div className="file-source">{item.source}</div>
                                    <div className="file-content">{item.content}</div>
                                    <div className="file-actions">
                                        {item.type === 'file' ? (
                                            <button
                                                type="button"
                                                className="btn btn-primary"
                                                onClick={() => downloadFile(item.content)}
                                                aria-label={`下载文件 ${item.content}`}
                                            >
                                                下载
                                            </button>
                                        ) : (
                                            <button
                                                type="button"
                                                className="btn btn-secondary"
                                                onClick={async () => {
                                                    try {
                                                        await navigator.clipboard.writeText(item.content);
                                                        showToast('复制成功！');
                                                    } catch {
                                                        const input = document.createElement('input');
                                                        input.value = item.content;
                                                        document.body.appendChild(input);
                                                        input.select();
                                                        document.execCommand('copy');
                                                        document.body.removeChild(input);
                                                        showToast('复制成功！');
                                                    }
                                                }}
                                                aria-label={`复制内容 ${item.content}`}
                                            >
                                                复制
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </main>

                <footer className="form-section">
                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            if (!select) {
                                showToast('请选择目标 IP！');
                                return;
                            }

                            const formData = new FormData(e.currentTarget);
                            const file = formData.get('file') as File | null;
                            const text = (formData.get('text') as string)?.trim();

                            if (file?.size) {
                                const data = new FormData();
                                data.append('target', select);
                                data.append('type', 'file');
                                data.append('file', file);
                                handleSubmit(data);
                                e.currentTarget.reset();
                            } else if (text) {
                                const data = new FormData();
                                data.append('target', select);
                                data.append('type', 'text');
                                data.append('text', text);
                                handleSubmit(data);
                                e.currentTarget.reset();
                            } else {
                                showToast('请输入内容或选择文件！');
                            }
                        }}
                    >
                        <div className="input-group">
                            <textarea
                                name="text"
                                placeholder="输入要发送的文本内容..."
                                rows={3}
                                aria-label="文本内容"
                            />
                            <input type="file" name="file" aria-label="选择文件" />
                        </div>
                        <div className="input-group">

                            <button
                                type="submit"
                                className="btn btn-submit"
                                disabled={loading || uploadLoading}
                                aria-busy={loading || uploadLoading}
                            >
                                {loading || uploadLoading ? '发送中...' : '发送'}
                            </button>
                        </div>
                    </form>
                </footer>


            </div>
            <Toast
                message={toast.message}
                show={toast.show}
                onClose={onCloseToast}
            />
        </div>
    );
};

export default Home;